import React, { forwardRef, useRef, useState } from 'react';
import { Button, Divider, Drawer, message, Popconfirm, Upload } from 'antd';
import request from '@/utils/request';
import type { ActionType } from '@ant-design/pro-table';
import ProTable from '@ant-design/pro-table';
import { PlusOutlined } from '@ant-design/icons';
import ReportEdit from './ReportEdit';
import UploadUtil from '@/components/UploadUtil';
import { useIntl } from 'umi';

const apiURL = '/api/services/app/ERPReports/';
const ReportList: React.FC<{ setCurrent: (item: any) => void; ref: any }> = forwardRef((props) => {
  const intl = useIntl();
  //const [form] = Form.useForm();
  const [loading, setLoading] = useState<boolean>(false);
  const [visible, setVisible] = useState<boolean>(false);
  const [, setRecord] = useState<any>([]);
  const [ReportClassOption, setReportClass] = useState<any>([]);
  const [params, setParams] = useState<any>({
    current: 1,
    pageSize: 10,
  });
  const pageSize = 10;
  const proTbRef = useRef<ActionType>();

  const fetchDatas = async (args: any = null) => {
    setLoading(true);
    const items: any = {
      data: [],
      total: 0,
    };
    await request(apiURL + 'GetList', {
      method: 'GET',
      params: {
        skipCount: (args.current - 1) * args.pageSize,
        maxResultCount: args.pageSize,
        keywords: args?.reportName,
        reportType: args?.reportType,
        classID: args?.classID,
      },
    }).then((response) => {
      if (response) {
        if (response.success) {
          items.data = response.result?.items;
          items.total = response.result?.totalCount;
        }
      }
      setLoading(false);
    });
    return items;
  };
  const GetReportClass = () => {
    request('/api/services/app/Category/GetTreeListAsync', {
      method: 'GET',
      params: { layout: 'ReportClass' },
    }).then((response) => {
      if (response) {
        if (response.success) {
          var arr: any = [];
          response.result.forEach((element: any) => {
            arr.push({
              label: element.categoryName,
              value: element.categoryIndex,
            });
          });
          setReportClass(arr);
        }
      }
    });
  };
  const setCurrent = (item?: any) => {
    if (props.setCurrent) {
      props.setCurrent(item);
    }
  };
  const doDel = (id: any) => {
    request(apiURL + 'Delete', {
      method: 'DELETE',
      params: { id },
    }).then((response) => {
      if (response) {
        if (response.success) {
          proTbRef.current?.reload();
        }
      }
    });
  };
  const doCopy = (id: any) => {
    request(apiURL + 'CopyReport', {
      method: 'POST',
      params: { id },
    }).then((response) => {
      if (response) {
        if (response.success) {
          proTbRef.current?.reload();
        }
      }
    });
  };
  const handlerImport = (info: any) => {
    if (info.file.status == 'error') {
      setLoading(false);
      message.error(intl.formatMessage({ id: 'pages.import.error' }));
    }
    if (info.file.status === 'done') {
      message.success(intl.formatMessage({ id: 'pages.import.success' }));
      setLoading(false);
    } else {
      setLoading(true);
    }
  };
  const handlerExport = async () => {
    setLoading(true);
    try {
      const resp = await request('/api/Excel/ExportERPReports', {
        method: 'POST',
        responseType: 'blob',
      });
      const url = window.URL.createObjectURL(resp);
      const a = document.createElement('a');
      a.href = url;
      a.download = 'ERPReports.xls';
      a.click();
    } catch (e) {
      message.error(intl.formatMessage({ id: 'export.error' }));
    }
    setLoading(false);
  };

  const columns = [
    {
      title: intl.formatMessage({ id: 'pages.reportName' }),
      dataIndex: 'reportName',
      width: 140,
    },
    {
      title: intl.formatMessage({ id: 'pages.memo' }),
      dataIndex: 'memo',
      width: 140,
    },
    {
      title: intl.formatMessage({ id: 'pages.reportType' }),
      dataIndex: 'reportType',
      valueType: 'select',
      fieldProps: {
        options: [
          {
            label: intl.formatMessage({id:'pages.systemReport'}),
            value: 'SysRpt',
          },
          {
            label: intl.formatMessage({id:'pages.userReport'}),
            value: 'UserRpt',
          },
        ],
      },
    },
    {
      title: intl.formatMessage({ id: 'pages.reportClass' }),
      dataIndex: 'classID',
      width: 140,
      valueType: 'select',
      fieldProps: {
        options: ReportClassOption,
      },
    },
    {
      title: intl.formatMessage({ id: 'pages.modularName' }),
      dataIndex: 'modularName',
      hideInSearch: true,
    },
    {
      title: intl.formatMessage({ id: 'pages.creationTime' }),
      dataIndex: 'creationTime',
      width: 200,
      hideInSearch: true,
      valueType: 'dateTime',
    },
    {
      title: intl.formatMessage({ id: 'pages.updateTime' }),
      dataIndex: 'lastModificationTime',
      width: 200,
      hideInSearch: true,
      valueType: 'dateTime',
    },
    {
      title: intl.formatMessage({ id: 'pages.operation' }),
      width: 200,
      hideInSearch: true,
      render: (_: any, rec: any) => (
        <span>
          <a onClick={() => setCurrent(rec)}>{intl.formatMessage({ id: 'pages.design' })}</a>
          <Divider type="vertical" />
          <a onClick={() => doCopy(rec.id)}>{intl.formatMessage({ id: 'pages.copy' })}</a>
          <Divider type="vertical" />
          <Popconfirm
            title={intl.formatMessage({ id: 'pages.delete?' })}
            onConfirm={() => doDel(rec.id)}
          >
            <a>{intl.formatMessage({ id: 'pages.delete' })}</a>
          </Popconfirm>
        </span>
      ),
    },
  ];
  const toolBar = [
    <Button type="primary" icon={<PlusOutlined />} onClick={() => setVisible(true)}>
      {intl.formatMessage({ id: 'pages.new' })}
    </Button>,
    <Upload
      accept=".xls,.xlsx,application/vnd.ms-excel"
      name="file"
      action={'/api/Excel/ImportERPReports'}
      headers={{
        Authorization: UploadUtil.accessToken,
      }}
      beforeUpload={UploadUtil.checkExcel}
      showUploadList={false}
      onChange={handlerImport}
    >
      <Button loading={loading}>{intl.formatMessage({ id: 'pages.import' })}</Button>
    </Upload>,
    <Button type="default" onClick={handlerExport} loading={loading}>
      {intl.formatMessage({ id: 'pages.export' })}
    </Button>,
  ];
  React.useEffect(() => {
    fetchDatas(params);
    GetReportClass();
  }, []);
  return (
    <>
      <ProTable
        columns={columns}
        actionRef={proTbRef}
        rowKey="id"
        key="id"
        bordered={false}
        request={async (args = {}) => {
          setParams(args);
          return fetchDatas(args);
        }}
        pagination={{
          pageSize,
        }}
        toolBarRender={() => toolBar}
        search={{
          filterType: 'light',
        }}
      />
      <Drawer
        title={intl.formatMessage({ id: 'pages.new' })}
        placement="right"
        closable={true}
        visible={visible}
        onClose={() => setVisible(false)}
        mask={true}
        maskClosable={true}
        destroyOnClose
        width={500}
      >
        <ReportEdit
          act="Create"
          callback={(resp: any) => {
            setRecord(resp);
            proTbRef.current?.reload();
          }}
        />
      </Drawer>
    </>
  );
});
export default ReportList;
